
#include <Texture2D.h>

Texture2D::Texture2D()
{
	mFilename = NULL;	
	mData = NULL;

	/*mFilename = new char[10];
	delete[] mFilename;
	mFilename = NULL;*/
}

Texture2D::~Texture2D()
{
	if(mFilename != NULL)
	{
		delete[] mFilename;
		mFilename = NULL;
	}

	if(mData != NULL)
	{
		delete[] mData;
		mData = NULL;
	}

}

void Texture2D::ConvertBGRtoRGB()
{
	const DWORD BitmapLength = mSizeX * mSizeY * 3;
	byte temp;

	for(DWORD i=0; i < BitmapLength; i+=3)
	{
		temp = mData[i];
		mData[i] = mData[i+2];
		mData[i+2] = temp;
	}

}

bool Texture2D::LoadFile(const char* inFilename)
{

	//checking for a existing file can go into utilities.
	if(!inFilename)		return false;

	mFilename = new char[strlen(inFilename)+1];
	for(size_t i=0;i<strlen(mFilename);i++)
		mFilename[i] = 0;
	strcpy(mFilename,inFilename);


	FILE *File = NULL;
	errno_t result = fopen_s(&File,mFilename,"r");
	if(result != 0)
		return false;
	else
		fclose(File);

	

	BITMAPINFO BMInfo;
	const HDC hdc = wglGetCurrentDC();

	BMInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
	BMInfo.bmiHeader.biBitCount = 0;

	HANDLE DIBHandle = LoadImage(0,mFilename,IMAGE_BITMAP,0,0,LR_DEFAULTCOLOR | LR_CREATEDIBSECTION | LR_LOADFROMFILE);

	if(DIBHandle == NULL)
		return false;

	GetDIBits(hdc,(HBITMAP)DIBHandle,0,0,NULL,&BMInfo,DIB_RGB_COLORS);
	mSizeX = BMInfo.bmiHeader.biWidth;
	mSizeY = BMInfo.bmiHeader.biHeight;
	BMInfo.bmiHeader.biBitCount = 24;
	BMInfo.bmiHeader.biCompression = BI_RGB;
	const DWORD BitmapLength = mSizeX * mSizeY  * 3;
	mData = new byte[BitmapLength];

	if(GetDIBits(hdc,(HBITMAP)DIBHandle,0,mSizeY, mData, &BMInfo, DIB_RGB_COLORS))
	{
		mIsReady = true;
		ConvertBGRtoRGB();
		glGenTextures( 1, &mTextureID );
		glBindTexture( GL_TEXTURE_2D, mTextureID );
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
		glTexImage2D( GL_TEXTURE_2D, 0, 3,mSizeX,mSizeY, 0,
			GL_RGB, GL_UNSIGNED_BYTE,mData );
		
	}

	if(mData == NULL)
	{
		delete[] mData;
		mData = NULL;
	}

	
	DeleteObject(DIBHandle);
	

	return mIsReady;
}